package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.service.MemberService;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Transactional
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Override
    public void addNewMember(String telephone) {
           //   根据手机号 查询  有无此用户
        QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("PHONENUMBER",telephone);
        Member member = baseMapper.selectOne(queryWrapper);
        if(member==null){
            member = new Member();
            member.setRegTime(new Date());  //
            member.setPhoneNumber(telephone);
            save(member);
        }

    }

    @Override
    public Map getMemberCount() {
        Map  map  = new HashMap();
        //   往前推送12个月
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);

        List<String>  yearAndMonth = new ArrayList<String>();
        List<Integer>  memberCounts = new ArrayList<Integer>();
  //  12个月的 会员数量统计
        for(int  i=1;i<=12;i++){
            Date time = calendar.getTime();//   2019-8
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String format = simpleDateFormat.format(time);
            yearAndMonth.add(format);// 12个月的 年-月  添加集合中

            String beginDate = format+"-1";
            String endDate = format+"-31";
            QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
            queryWrapper.between("REGTIME",beginDate,endDate);
            int memberCountPerMonth = count(queryWrapper);
            memberCounts.add(memberCountPerMonth);//  每个月的会员数量统计
            calendar.add(Calendar.MONTH,1);//  循环一次 往后推送一个月
        }

        map.put("memberCounts",memberCounts);
        map.put("yearAndMonth",yearAndMonth);
        return map;
    }

    @Override
    public List<Map> getMemberPercentageBySex() {
       return baseMapper.getMemberPercentageBySex();
    }

    @Override
    public List<Map> getMemberAgeGroup() {
        return baseMapper.getMemberAgeGroup();
    }
}
